package com.github.caijh.mall.utils;

import java.util.List;
import java.util.UUID;

import com.github.caijh.commons.util.Strings;
import com.github.caijh.framework.core.exception.BizException;
import com.github.caijh.mall.upload.vo.FileResultVo;
import lombok.Data;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

@Data
public class UploadContext {


    private boolean isCompress = false;

    private UploadSpecs uploadSpecs;

    private UploadStrategy strategy;


    public UploadContext(UploadSpecs specs, UploadStrategy strategy) {
        this.uploadSpecs = specs;
        this.strategy = strategy;
    }


    public FileResultVo upload(MultipartFile multipartFile, UploadSpecs specs) {
        if (null == multipartFile || multipartFile.isEmpty()) {
            throw BizException.of("UPLOAD_EXCEPTION_FILE_NOT_FOUND");
        }
        String fileName = multipartFile.getOriginalFilename();
        String extName = FilenameUtils.getExtension(fileName);

        checkExt(extName);

        //文件大小验证
        checkSize(multipartFile.getSize());

        String newFileName = UUID.randomUUID().toString().replace("-", "") + "." + extName;
        specs.setNewFileName(newFileName);
        specs.setExtName(extName);

        return this.strategy.upload(multipartFile, specs);
    }

    /**
     * 检查扩展名.
     *
     * @param extName 扩展名
     */
    private void checkExt(String extName) {
        if (StringUtils.isEmpty(extName)) {
            throw BizException.of("UPLOAD_EXCEPTION_FILE_EXT_NULL");
        }

        String extSupported = this.getUploadSpecs().getExtSupported();
        if (StringUtils.isNotEmpty(extSupported)) {
            List<String> extensions = Strings.toListByComma(extSupported);
            if (!extensions.isEmpty()) {
                if (!extensions.contains(extName)) {
                    throw BizException.of("UPLOAD_EXCEPTION_FILE_EXT_SUPPORTED", extName);
                }
            } else {
                throw BizException.of("UPLOAD_EXCEPTION_FILE_EXT_SUPPORTED", extName);
            }
        }
    }

    private void checkSize(Long size) {
        long limitSize = this.uploadSpecs.getLimitSize();
        if (size > limitSize) {
            throw BizException.of("UPLOAD_EXCEPTION_FILE_SIZE", size / 1024 / 1024, limitSize / 1024 / 1024);
        }
    }

}
